import {todoListState, useRecoilState} from "../../recoils";
import React from "react";

export default function TodoItem({item}) {
    const [todoList, setTodoList] = useRecoilState(todoListState);
    const index = todoList.findIndex((listItem) => listItem.id === item.id);

    const editItemValue = (event) => {
        const value = event.target.value;
        const newList = replaceItemAtIndex(todoList, index, {
            ...item,
            value,
        });
        setTodoList(newList);
    }

    const toggleItemCompletion = () => {
        const newList = replaceItemAtIndex(todoList, index, {
            ...item,
            isComplete: !item.isComplete,
        });

        setTodoList(newList);
    };

    const deleteItem = () => {
        const newList = removeItemAtIndex(todoList, index);
        setTodoList(newList);
    };

    return (
        <div  style={{padding: '15px'}}>
            <form className="form-inline">
                <div className="form-group">
                    <input className="form-control" type="text" value={item.value} onChange={editItemValue}/>
                </div>
                <div className="form-group" style={{padding: "0 10px"}}>
                    <input
                        type="checkbox"
                        checked={item.isComplete}
                        onChange={toggleItemCompletion}
                    />
                </div>
                <button type="button" className="btn btn-danger btn-sm" onClick={deleteItem}>删除</button>
            </form>


        </div>
    );
}

function replaceItemAtIndex(arr, index, newValue) {
    return [...arr.slice(0, index), newValue, ...arr.slice(index + 1)];
}

function removeItemAtIndex(arr, index) {
    return [...arr.slice(0, index), ...arr.slice(index + 1)];
}
